class Order < ActiveRecord::Base
  belongs_to :user
  belongs_to :address
  belongs_to :logistic
  has_many   :line_items,:dependent=>:delete_all
  #  before_save :calculate_logistic_fee
  #  has_and_belongs_to_many :products, :join_table =>:line_items
  PAYTYPE = [
    [ "货到付款",   1 ],
    [ "支付宝",   2 ]
  ]

  SHIPPING_TYPE = [
    [ "送货上门",   1 ],
    [ "自取",   2 ]
  ]

  STATUS = [

    [ "待确认",1],
    [ "配货中",2],
    [ "交易完成",3],
    [ "交易取消",4]

  ]

  def add_line_items_from_cart(cart)
    cart.items.each do |item|
      li = LineItem.from_cart_item(item)
      line_items << li
    end
  end

  def calculate_logistic_fee
    if self.logistic_id && self.address_id && self.total_item < self.logistic.free_quantity
      logistic_fee = LogisticFee.find_by_province_id_and_logistic_id(self.address.province_id,self.logistic_id)
      self.logistics_fee = logistic_fee ? logistic_fee.fee : self.logistic.default_fee
    end
  end

  def self.undeal_order_total_price
    self.find_all_by_status(1).inject(0) { |sum,item| sum+item.total_price }
  end

  def total_price
    line_items.inject(0) { |sum,item| sum+item.total_price } + self.logistics_fee
  end

  def total_product_price
    line_items.inject(0) { |sum,item| sum+item.total_price }
  end

  def total_item
    line_items.inject(0) { |sum,item| sum+item.quantity }
  end

  def self.filter_order(status,start_date,end_date)
    self.find(:all,:conditions=>['status = ? and created_at between ? and ?',status,start_date,end_date])
  end

  def set_status_paid
    self.status = 2
  end

  def set_status_complate
    self.status = 5
  end

  def calculate_point(order_hash)
    self.transaction() do
      self.update_attributes(order_hash)
      self.user.point += self.total_product_price.to_i
      self.user.save
      if self.user.recommender
        self.user.recommender.point += self.total_product_price.to_i/2
        self.user.recommender.save
      end
    end
  end

  def save_and_decrease_user_point
    self.transaction() do
      user = self.user
      point = (self.used_point < user.point ?  self.used_point : user.point)
      user.point -= point
      self.user.save
      self.used_point = point
      self.save
    end
  end
end
